package de.fstyle.android.worldcanvas.fragments;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;

public class LocationFragment 
extends Fragment
implements
		GooglePlayServicesClient.ConnectionCallbacks,
		GooglePlayServicesClient.OnConnectionFailedListener {

	public static final String LOG_TAG = "location_fragment";
	
	/**
	 * Request code to send to Google Play services.
	 * This code is returned in onActivityResult(...).
	 */
	private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

	protected LocationClient locationClient;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.locationClient = new LocationClient(
				this.getActivity(), 
				this, 
				this);
	}
	
	
	/**
	 * Handle results returned to the Fragment by Google Play services.
	 */
	@Override
	public void onActivityResult(
			int requestCode,
			int resultCode, 
			Intent data) {
		
		// Decide what to do based on the original request code
		switch (requestCode) {
		case CONNECTION_FAILURE_RESOLUTION_REQUEST:
			/*
			 * If the result code is Activity.RESULT_OK, try to connect again
			 */
			switch (resultCode) {
			case Activity.RESULT_OK:
				/*
				 * Try the request again
				 */
				servicesConnected();
				break;
			}
		}
	}
	
	@Override
	public void onStart() {
		super.onStart();
		this.locationClient.connect();
	}
	
	@Override
	public void onStop() {
		this.locationClient.disconnect();
		super.onStop();
	}

	/**
	 * Called by Location Services when the request to connect the client
	 * finishes successfully. 
	 * At this point, you can request the current location or start periodic 
	 * updates.
	 */
	@Override
	public void onConnected(Bundle dataBundle) {
		
		// display the connection status
		Toast.makeText(
				this.getActivity(), 
				"Connected", 
				Toast.LENGTH_SHORT).show();

	}

	/*
	 * Called by Location Services if the connection to the location client
	 * drops because of an error.
	 */
	@Override
	public void onDisconnected() {
		
		// display the connection status
		Toast.makeText(
				this.getActivity(), 
				"Disconnected. Please re-connect.",
				Toast.LENGTH_SHORT).show();
	}

	/*
	 * Called by Location Services if the attempt to Location Services fails.
	 */
	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
		/*
		 * Google Play services can resolve some errors it detects. If the error
		 * has a resolution, try sending an Intent to start a Google Play
		 * services activity that can resolve error.
		 */
		if (connectionResult.hasResolution()) {
			try {
				// start an Activity that tries to resolve the error
				connectionResult.startResolutionForResult(
						this.getActivity(),
						CONNECTION_FAILURE_RESOLUTION_REQUEST);
				/*
				 * Thrown if Google Play services canceled the original
				 * PendingIntent
				 */
			} catch (IntentSender.SendIntentException e) {
				// Log the error
				e.printStackTrace();
			}
		} else {
			/*
			 * If no resolution is available, display a dialog to the user with
			 * the error.
			 */
			showErrorDialog(
					connectionResult.getErrorCode(),
					CONNECTION_FAILURE_RESOLUTION_REQUEST);
		}
	}

	protected boolean servicesConnected() {
		
		// Check that Google Play services is available
		int resultCode = 
				GooglePlayServicesUtil.isGooglePlayServicesAvailable(
						this.getActivity());
		Log.d(LOG_TAG, 
				"Google play result code: " + resultCode 
				+ " (success: " + ConnectionResult.SUCCESS + ")");
		
		// If Google Play services is available
		if (ConnectionResult.SUCCESS == resultCode) {
			
			// In debug mode, log the status
			Log.d(LOG_TAG, "Google Play services is available.");
			
			// Continue
			return true;
		
		// Google Play services was not available for some reason
		} else {
			
			this.showErrorDialog(
					resultCode, 
					CONNECTION_FAILURE_RESOLUTION_REQUEST);
			
			return false;
		}
	}
	
	private void showErrorDialog(int resultCode, int requestCode) {
		
		// Get the error dialog from Google Play services
		Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
				resultCode,
				this.getActivity(), 
				requestCode);
		
		// If Google Play services can provide an error dialog
		if (errorDialog != null) {
			
			// Create a new DialogFragment for the error dialog
			ProxyDialogFragment errorFragment = new ProxyDialogFragment();
			
			// Set the dialog in the DialogFragment
			errorFragment.setDialog(errorDialog);
			
			// Show the error dialog in the DialogFragment
			errorFragment.show(
					this.getFragmentManager(),
					LOG_TAG);
		}
	}
}
